import { Box, DialogContent, DialogTitle, Typography } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import create from 'zustand';

import Member from '../../../../api/member/member';
import MemberManager from '../../../../api/member/member-manager';
import { isEmailInvalid, isWalletAddressInvalid } from '../../../../libs/validate';
import { GFSLoadingButton } from '../../button/gfs-button';
import { GfsInputBase, GfsInputLabel, StyledErrorText } from '../../forms';
import GFSDialog from '../gfs-dialog';
import { useStyles } from '../UIs/styled-mui-dialog';

interface ModifyScholarStore {
    open: boolean;
    close?: () => void;
    data: ModifyScholarData;
    onSubmit?: (any) => void;
}

export interface ModifyScholarData {
    type: 'create' | 'update';
    item?: any;
}

const useModifyStore = create<ModifyScholarStore>((set) => ({
    open: false,
    close: () => set({ open: false }),
    data: {} as ModifyScholarData,
    onSubmit: undefined
}));

export const modifyScholarDialog = ({ data, onSubmit }: ModifyScholarStore) => {
    useModifyStore.setState({
        open: true,
        data,
        onSubmit
    });
};

export const ModifyScholarDialog = () => {
    const style = useStyles();
    const { open, close, data, onSubmit } = useModifyStore();
    const { type = 'create', item } = data;
    const [memberRoninWalletAddress, setMemberRoninWalletAddress] = useState<string>(
        item?.memberRoninWalletAddress
    );
    const [gameWalletAddress, setGameWalletAddress] = useState<string>(
        item?.managerRoninWalletAddress
    );
    const [name, setName] = useState<string>(item?.name);
    const [email, setEmail] = useState<string>(item?.email);
    const [loading, setLoading] = useState<boolean>(false);

    useEffect(() => {
        setMemberRoninWalletAddress(item?.memberRoninWalletAddress);
        setGameWalletAddress(item?.managerRoninWalletAddress);
        setName(item?.name);
        setEmail(item?.email);
    }, [item]);

    const onReceivingWalletAddressChange = (event) => {
        setMemberRoninWalletAddress(event.target?.value);
    };

    const isReceivingWalletAddressError = () => {
        return (
            memberRoninWalletAddress !== undefined &&
            isWalletAddressInvalid(memberRoninWalletAddress)
        );
    };
    const onGameWalletAddressChange = (event) => {
        setGameWalletAddress(event.target?.value);
    };

    const isGameWalletAddressError = () => {
        return gameWalletAddress !== undefined && isWalletAddressInvalid(gameWalletAddress);
    };

    const onNameChange = (event) => {
        setName(event.target?.value);
    };

    const isNameError = () => {
        return name !== undefined && typeof name === 'string' && name.trim() === '';
    };

    const onEmailChange = (event) => {
        setEmail(event.target?.value);
    };

    const isEmailError = () => {
        return email !== undefined && isEmailInvalid(email);
    };

    const isFormError = () => {
        return (
            !name ||
            !memberRoninWalletAddress ||
            !gameWalletAddress ||
            isReceivingWalletAddressError() ||
            isGameWalletAddressError() ||
            isEmailError() ||
            isEmailError()
        );
    };

    const onAddScholar = async () => {
        if (isFormError()) {
            return;
        }
        setLoading(true);
        try {
            const body: Partial<Member> = {
                managerRoninWalletAddress: gameWalletAddress,
                memberRoninWalletAddress: memberRoninWalletAddress,
                name,
                email,
                ...(item?.id && { id: item.id })
            };
            const data = await MemberManager[type](body);
            onSubmit(data);
            toast.success(`${type === 'create' ? 'Create' : 'Update'} member successfully!`, {
                theme: 'dark'
            });
        } catch (e) {
            toast.error(e.message || `Cannot ${type} member!`, { theme: 'dark' });
        } finally {
            setLoading(false);
            setMemberRoninWalletAddress(undefined);
            setGameWalletAddress(undefined);
            setName(undefined);
            setEmail(undefined);
            close();
        }
    };

    return (
        <GFSDialog open={open}>
            <DialogTitle>
                {type === 'create' ? 'New' : 'Edit'} Member
                <Box
                    component="img"
                    alt="Icon"
                    src={'/close.svg'}
                    sx={{ cursor: 'pointer' }}
                    onClick={close}
                />
            </DialogTitle>
            <DialogContent className={`${style.center}`}>
                <Box sx={{ p: 4, pt: 2, width: '100%' }}>
                    <Box mb={4} position="relative">
                        <GfsInputLabel shrink htmlFor="manager-wallet-address-input">
                            Manager's Ronin Wallet Address
                            {/* <Box*/}
                            {/*    component="img"*/}
                            {/*    alt="Icon"*/}
                            {/*    src={'/tooltip.svg'}*/}
                            {/*    sx={{ cursor: 'pointer', ml: 1 }}*/}
                            {/* />*/}
                        </GfsInputLabel>
                        <GfsInputBase
                            id="manager-wallet-address-input"
                            onChange={onGameWalletAddressChange}
                            className={isGameWalletAddressError() ? 'error' : ''}
                            value={gameWalletAddress || ''}
                        />
                        {isGameWalletAddressError() && (
                            <StyledErrorText variant={'subtitle2'}>
                                Invalid wallet address
                            </StyledErrorText>
                        )}
                    </Box>
                    <Box mb={4} position="relative">
                        <GfsInputLabel shrink htmlFor="name">
                            Member Name
                        </GfsInputLabel>
                        <GfsInputBase
                            id="name"
                            onChange={onNameChange}
                            value={name || ''}
                            className={isNameError() ? 'error' : ''}
                        />
                        {isNameError() && (
                            <StyledErrorText variant={'subtitle2'}>Required</StyledErrorText>
                        )}
                    </Box>
                    <Box mb={5} position="relative">
                        <GfsInputLabel shrink htmlFor="email">
                            Email Address
                        </GfsInputLabel>
                        <GfsInputBase
                            id="email"
                            onChange={onEmailChange}
                            value={email || ''}
                            className={isEmailError() ? 'error' : ''}
                        />
                        {isEmailError() && (
                            <StyledErrorText variant={'subtitle2'}>
                                Invalid email address
                            </StyledErrorText>
                        )}
                    </Box>
                    <Box mb={5} position="relative">
                        <Typography sx={{ color: '#FFBB59', pb: 3 }}>
                            Member's Wallet addresses
                        </Typography>
                        <GfsInputLabel shrink htmlFor="receiving-wallet-address-input">
                            Ronin
                        </GfsInputLabel>
                        <GfsInputBase
                            id="receiving-wallet-address-input"
                            onChange={onReceivingWalletAddressChange}
                            value={memberRoninWalletAddress || ''}
                            className={isReceivingWalletAddressError() ? 'error' : ''}
                        />
                        {isReceivingWalletAddressError() && (
                            <StyledErrorText variant={'subtitle2'}>
                                Invalid wallet address
                            </StyledErrorText>
                        )}
                    </Box>

                    {/* {type === 'create' && (*/}
                    {/*    <Box pb={4} className="d-flex align-items-baseline">*/}
                    {/*        <Box*/}
                    {/*            component="img"*/}
                    {/*            alt="Icon"*/}
                    {/*            src={'/tooltip.svg'}*/}
                    {/*            sx={{ mr: 1.5, width: '1.5rem' }}*/}
                    {/*        />*/}
                    {/*        <Typography>*/}
                    {/*            Insert content here (Once user clicks on Add Member button, we will*/}
                    {/*            automatically send the invite to the member’s email).*/}
                    {/*        </Typography>*/}
                    {/*    </Box>*/}
                    {/* )}*/}

                    <GFSLoadingButton
                        onClick={onAddScholar}
                        fullWidth
                        disabled={isFormError()}
                        loading={loading}
                    >
                        {type === 'create' ? 'Add' : 'Update'} Member
                    </GFSLoadingButton>
                </Box>
            </DialogContent>
        </GFSDialog>
    );
};
